package com.example.shirodemo.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.example.shirodemo.constant.HttpCode;
import com.example.shirodemo.controller.vo.UserInfoVo;
import com.example.shirodemo.dto.ResponseResult;
import com.example.shirodemo.dto.ResponseResultPage;
import com.example.shirodemo.entity.SUser;
import com.example.shirodemo.service.AdminService;
import com.example.shirodemo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author 绫小路
 * @Date 2021/1/13
 */
@Api(tags="05-后台页面：用户管理 - UserAdminController")
@Controller
@RequestMapping("/admin/user")
public class UserAdminController {

  @Autowired
  private HttpServletRequest request;
  @Autowired
  private AdminService adminService;
  @Autowired
  private UserService userService;

  @ApiOperation("后台管理获取用户列表/搜索")
  @GetMapping("/list")
  @ResponseBody
  public ResponseResultPage list(Integer page, Integer limit, String search) {
    if ((page != null && (page < 1 || page > 100)) ||
        (limit != null && (limit < 1 || limit > 100))) {
      return new ResponseResultPage(HttpCode.FAIL, "入参page、limit范围分别是：1~100、1~100");
    }
    if (page == null) {
      page = 1;
    }
    if (limit == null) {
      limit = 10;
    }
    return adminService.getUserList(page, limit, search);
  }

  @ApiOperation("获取用户信息")
  @GetMapping("info")
  @ResponseBody
  public ResponseResult info(Integer userId) {
    Assert.isFalse(userId == null, "入参userId不能为空！");
    SUser user = userService.getUserById(userId);
    UserInfoVo infoVo = BeanUtil.copyProperties(user, UserInfoVo.class);
    return new ResponseResult(HttpCode.OK, infoVo);
  }

  @ApiOperation("后台管理更新用户信息")
  @PostMapping("update")
  @ResponseBody
  public ResponseResult update(String password, String cpassword, Integer userId) {
    Assert.isFalse(userId == null, "入参userId不能为空！");
    Assert.notBlank(password, "入参password不能为空");
    Assert.notBlank(cpassword, "入参cpassword不能为空");
    Assert.isFalse(!password.equals(cpassword), "两次出入的密码不一致！");
    Assert.isFalse(password.length() < 0 || password.length() > 21, "密码长度：1~20");
    return userService.updatePassword(userId, password);
  }

}
